package com.example.tms.common.config;
import java.security.Principal;
import java.util.Optional;

import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import com.example.tms.mapper.SystemLogMapper;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/*
 *无他，唯手熟尔
 */
// LogInterceptor.java
@Component
public class LogInterceptor implements HandlerInterceptor {

    @Autowired
    private SystemLogMapper systemLogMapper;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 从请求中获取用户信息（示例）
        String userId = Optional.ofNullable(request.getUserPrincipal())
                .map(Principal::getName) // 或者获取ID的其他方式
                .orElse("SYSTEM"); // 系统操作标记
        // 优化IP获取逻辑
        String ip = Optional.ofNullable(request.getHeader("X-Forwarded-For"))
                .map(xff -> xff.split(",")[0].trim())
                .orElse(request.getRemoteAddr());

        // 放入MDC
        MDC.put("user", userId);
        MDC.put("ip", ip);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        MDC.clear();
    }
}
